<?php
namespace app\api\logic;

use think\Db;
use think\Controller;
use app\api\model\BillStripe;
use app\api\model\TradeStripe;
use app\api\service\Paystripe;

/**
 * Stripe 支付
 * @author sam
 * Date 2019/07/15
 */
class StripeLogic extends Controller
{

    // 协议支付
    public function payAgree($tradeId)
    {
        // 获取请求信息
        $data = $this->getInfo($tradeId);
        // 实例化支付
        $pay = new Paystripe();
        // 查询CustomerId
        $info = $this->findBill($data['user_id']);
        // customerId存在时发起支付
        if (!empty($info)) {
            $data['goods_amount'] = ceil($data['goods_amount']*100);
            $res = $pay->createCharge($data['goods_amount'], $data['goods_unit'], $info['customer_id']);
            if (!empty($res->status) && strtolower($res->status) == "succeeded") {
                $this->saveTrade($tradeId, $info['bill_id']);
                return $this->returnMsg(200, 1);
            }else{
                $this->delTrade($tradeId);
                $this->saveBill($info['bill_id']);
                return $this->returnMsg(107, 0, $res);
            }
        }else{
            return false;
        }
    }

    // 创建支付
    public function payment($param)
    {
        $tradeId = $param['trade_id'];
        $tokenId = $param['stripeToken'];
        // 验参
        if (empty($tradeId)) return $this->returnMsg(103);
        if (empty($tokenId)) return $this->returnMsg(105);

        // 获取请求信息
        $data = $this->getInfo($tradeId);
        // 实例化
        $pay = new Paystripe();
        // Create Customer
        $res = $pay->createCustomer($tokenId);
        if (!empty($res['message'])) {
            $this->delTrade($tradeId);
            return $this->returnMsg(106, 0, $res);
        }else{
            // 保存数据库
            $billId = $this->saveCustomerId($res->id, $data['user_id']);
            if (empty($billId)) return $this->returnMsg(104);
        }

        // Create Charge
        $data['goods_amount'] = ceil($data['goods_amount']*100);
        $res = $pay->createCharge($data['goods_amount'], $data['goods_unit'], $res->id);
        if (!empty($res->status) && strtolower($res->status) == "succeeded") {
            $this->saveTrade($tradeId, $billId);
            return $this->returnMsg(200, 1);
        }else{
            $this->delTrade($tradeId);
            return $this->returnMsg(107, 0, $res);
        }

    }

    // 保存请求信息
    public function saveRequest($data)
    {
        $list = [
            'user_id'      => $data['user_id'],
            'goods_title'  => $data['goods_title'],
            'goods_desc'   => $data['goods_desc'],
            'goods_amount' => $data['goods_amount'],
            'goods_unit'   => $data['goods_unit'],
        ];

        // 请求参数
        $list['request_ip']    = getClientIp();
        $list['request_param'] = serialize($data);
        $list['create_time']   = date("y-m-d H:i:s", time());

        // 保存数据库
        $insertId = Db::name('trade_stripe')->insertGetId($list);
        return $insertId;
    }

    // 获取交易记录信息
    public function getInfo($id)
    {
        return TradeStripe::get($id);
    }

    // 更新交易记录表bill_id
    public function saveTrade($trade_id, $bill_id)
    {
        $trade = new TradeStripe;
        $res   = $trade::where('trade_id', $trade_id)->update(['bill_id' => $bill_id, 'status' => 1]);
        return $res;
    }

    // 删除交易记录
    public function delTrade($id)
    {
        $bill = new TradeStripe;
        return $bill::where('trade_id', $id)->delete();
    }


    // 保存交易ID到数据库
    public function saveCustomerId($id, $userId)
    {
        $bill = new BillStripe;
        $bill->customer_id = $id;
        $bill->user_id     = $userId;
        $bill->create_time = date("y-m-d H:i:s", time());
        $bill->save();

        return $bill->bill_id;
    }

    // 删除customerId
    public function delCustomer($customerId)
    {
        $bill = new BillStripe;
        return $bill::where('customer_id', $customerId)->delete();
    }


    // 查询交易ID
    public function findBill($userId)
    {
        $bill = new BillStripe;
        $info = $bill->where('user_id', $userId)->where('status', 1)->find();
        return $info;
    }

    // 更新交易ID状态
    public function saveBill($billId)
    {
        $bill = new BillStripe;
        $res   = $bill::where('bill_id', $billId)->update(['status' => -1]);
        return $res;
    }

    /**
     * 接口输出
     *
     * @param      intval   $code     错误代码
     * @param      boolean  $status   请求结果
     * @param      array    $data     参数
     * @param      string   $apiMsg   接口返回信息
     *
     * @return     array    ( response )
     */
    public function returnMsg($code, $status = false, $arr = [])
    {
        $msg  = config("logic.stripe_msg");
        $data = [
            'result'   => empty($status)? "fail": "success",
            'code'     => $code,
            'message'  => $msg[$code],
            'api_code' => empty($arr['code'])? '': $arr['code'],
            'api_msg'  => empty($arr['message'])? '': $arr['message'],
            'data'     => $arr,
        ];

        return json($data);
    }
}
